import axios from 'axios'
import qs from 'qs'
import router from '../router'
import { Loading, Message } from 'element-ui'

import refreshToken from './refreshToken'
import global_ from './base.js'
import { getToken } from '@/utils/auth'
// 1.创建axios的实例
const instance = axios.create({
  baseURL: global_.BASE_URL,
  timeout: 5000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})
// 配置通用请求动画
let loading = null

let isLock = true
// 2.axios拦截器
// 请求拦截 instance.interceptors.request.use()
instance.interceptors.request.use(

  config => {
    config.headers.Authorization = getToken()// window.sessionStorage.getItem('token') // 必须在请求头中使用 `Authorization` 字段提供 `token` 令牌
    config.data = qs.stringify(config.data) // 转为formdata数据格式
    loading = Loading.service({
      lock: true,
      text: '拼命加载中...',
      background: 'rgba(255, 255, 255, 0)'
    })
    return config
  },
  err => {
    console.log(err)
    loading.close() // 关闭请求动画
    return Promise.reject(err)
  }
)
// 响应拦截
instance.interceptors.response.use(async(response) => {
  // console.log(response.data)
  // console.log('isLock 0=', isLock)
  // 前端拦截登录状态
  const refreshJwt = window.sessionStorage.getItem('token_refresh')
  if (response && response.data) {
    // console.log('response=', response)
    // console.log('response.data.code=', response.data.code)
    switch (Number(response.data.code)) {
      case 0: // 登录失败
      // data = response.data
        break
      case 200: // 正常
        // data = response.data
        break
      case 103: // token过期

        if ((refreshJwt !== 'undefined' && refreshJwt) && isLock) {
          await refreshToken(response)
          isLock = false // 这里防止并发的时候造成死循环,所以要加锁

          // 刷新完成,继续之前的请求
          response.config.headers.Authorization = window.sessionStorage.getItem('token')
          const result = await instance.post(response.config.url, qs.parse(response.config.data)) // error.config 包含了当前请求的所有信息
          if (result) {
            response = result
            isLock = true
          }
        } else {
          // console.log('else')
          Message.error(response.data.msg || `身份过期，请重新登录!`)
          if (router.currentRoute.path !== '/login') {
            setTimeout(() => {
              router.replace({ path: '/login', query: { redirect: router.currentRoute.fullPath }})
            }, 1200)
          }
        }

        break
      case 403: // 无权限
        router.push('/login')
        break
      default:
        // Message.error({
        //   message: response.data.msg
        // })
        // router.push('/login')
        break
    }
  }
  // if (response.data.meta.status === -1) {
  // location.href = '/login'
  // alert('权限错误，请重新登录！')
  // this.$message.error(response.data.meta.msg)
  // return router.push('/login')
  // }
  loading.close() // 关闭请求动画
  return response
}, err => {
  loading.close() // 关闭请求动画
  return Promise.resolve(err.response)
})
/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function get(url, params) {
  return new Promise((resolve, reject) => {
    instance.get(url, {
      params: params
    }).then(response => {
      resolve(response.data)
    }).catch(err => {
      reject(err.data)
    })
  })
}

/**
* post方法，对应post请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function post(url, data = {}) {
  // console.log(data)
  return new Promise((resolve, reject) => {
    instance.post(url, data)
      .then(response => {
        // console.log('repponse=' + response)
        /* if (response.data.meta.status === -1) {
          this.$message.error(response.data.meta.msg)
          alert('权限错误，请重新登录！')
          router.push('/login')
        } */
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}
/**
* postblob方法，对应postblob请求
* @param {String} url [请求的url地址]
* @param {Object} params [请求时携带的参数]
*/
export function postblob(url, data = {}) {
  return new Promise((resolve, reject) => {
    instance.post(url, data, { responseType: 'blob' })
      .then(response => {
        if (response.code === -1) {
          this.$message.error(response.data.meta.msg)
          alert('权限错误，请重新登录！')
          router.push('/login')
        }
        resolve(response)
      })
      .catch(err => {
        reject(err)
      })
  })
}
